package DataStructure_ZL.搜索树哈希和mapset.实现简单的哈希;

//简单的实现哈希表的部分功能
public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int NodeSize;
    public static final double DEFAULT_LOAD_FACTOR = 0.75;

    public HashBuck() {
        this.array = new Node[8];
    }

    //存放元素
    public void put(int key, int val) {
        int index = key % array.length;
        Node node = new Node(key, val);
        Node cur = array[index];
        //遍历 index下标 的链表
        //  1. 查看是否有一样的key，有一样的替换val值 2. 没有的话 进行头插法
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
            }
            cur = cur.next;
        }
        //到这里说明没有相同的key，进行插入
        node.next = array[index];
        array[index] = node;
        NodeSize++;
        //检查 当前哈希表中 是否超过了指定的负载因子
        if (NodeSize * 1.0 / array.length > DEFAULT_LOAD_FACTOR) {
            //调用扩容方法

        }

    }

    //对数组进行扩容
    private void resize() {
        Node[] temp = new Node[2 * array.length];
        int index;
        Node cur;
        for (int i = 0; i < array.length; i++) {
            cur = array[i];
            index = cur.key % temp.length;
            Node curNext;
            if (cur != null) {//i位置有节点
                while (cur != null) {
                    //将节点迁移到新的数组中(头插法，应该用尾插但更麻烦一点)
                    curNext = cur.next;
                    cur.next = temp[index];
                    temp[index] = cur;
                    cur = curNext;
                }
            } else {//i位置没有节点
                temp[index] = array[i];
            }
        }
        array = temp;
    }

    //根据key值获取val值
    public int get(int key) {
        int inedex = key % array.length;
        Node cur = array[inedex];
        while (cur != null) {
            if (cur.key == key) return cur.val;
        }
        return -1;
    }

}
